﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Diagnostics;

namespace BaseTypesControlLib.Controls
{
    public class HorizontalManager : ManagerPanel
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="availableSize">size given by parent.The available size 
        /// that this element can give to child elements.</param>
        /// <returns>the size the panel decides it needs</returns>
        protected override Size MeasureOverride(Size availableSize)
        {
            Size sizeForChildren = availableSize;
            if (HorizontalScroll)
                sizeForChildren.Width = MAX_SIZE;
            if (VerticalScroll)
                sizeForChildren.Height = MAX_SIZE;

            Size sz = new Size();
            UIElement prevItem = null;
            for (int i = 0; i < Children.Count; i++)
            {
                UIElement item = Children[i];
                if (prevItem != null)
                {
                    sizeForChildren.Width -= prevItem.DesiredSize.Width;
                    if (sizeForChildren.Width < 0) sizeForChildren.Width = 0;
                }
                item.Measure(sizeForChildren);
                sz.Width += item.DesiredSize.Width;
                sz.Height = Math.Max(sz.Height, item.DesiredSize.Height);
                prevItem = item;
            }

            if (sz.Width > availableSize.Width) sz.Width = availableSize.Width;
            if (sz.Height > availableSize.Height) sz.Height = availableSize.Height;


            if (UseAllWidth && sz.Width < availableSize.Width) sz.Width = availableSize.Width;
            if (UseAllHeight && sz.Height < availableSize.Height) sz.Height = availableSize.Height;

            //Debug.WriteLine(string.Format("{4}: cw={0}, ch={1}, aw={2}, ah={3}", availableSize.Width, availableSize.Height, sz.Width, sz.Height, GetType().Name));
            return sz;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="finalSize">The final area within the parent that this 
        /// element should use to arrange itself and its children.</param>
        /// <returns>the actual size used by the control</returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            double x = 0;
            for (int i = 0; i < Children.Count; i++)
            {
                UIElement item = Children[i];
                item.Arrange(new Rect(new Point(x, 0), new Size(item.DesiredSize.Width, DesiredSize.Height)));
                x += item.DesiredSize.Width;
            }

            return DesiredSize;
        }
    }
}
